using Microsoft.AspNetCore.Mvc;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 审计系统测试控制器
    /// </summary>
    [ApiController]
    [Route("api/test/audit")]
    public class AuditTestController : ControllerBase
    {
        private readonly IAuditService _auditService;
        private readonly ILogger<AuditTestController> _logger;

        public AuditTestController(
            IAuditService auditService, 
            ILogger<AuditTestController> logger)
        {
            _auditService = auditService;
            _logger = logger;
        }

        /// <summary>
        /// 测试基本审计日志记录功能
        /// </summary>
        [HttpPost("test-log")]
        public async Task<IActionResult> TestAuditLog()
        {
            try
            {
                var testEntry = new AuditLogEntry
                {
                    TenantId = "test-tenant-001",
                    UserId = "test-user-001",
                    UserName = "Test User",
                    Action = "TestAction",
                    ResourceType = "TestResource",
                    ResourceId = "test-resource-001",
                    Description = "This is a test audit log entry",
                    IpAddress = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "Unknown",
                    UserAgent = HttpContext.Request.Headers["User-Agent"].ToString(),
                    Result = "Success",
                    Timestamp = DateTime.UtcNow
                };

                await _auditService.LogAsync(testEntry);

                return Ok(new
                {
                    message = "审计日志测试成功",
                    entry = new
                    {
                        testEntry.TenantId,
                        testEntry.Action,
                        testEntry.ResourceType,
                        testEntry.Timestamp
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "审计日志测试失败");
                return StatusCode(500, new { message = "测试失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 测试获取审计统计信息
        /// </summary>
        [HttpGet("test-stats/{tenantId}")]
        public async Task<IActionResult> TestGetStatistics(string tenantId)
        {
            try
            {
                var stats = await _auditService.GetStatisticsAsync(tenantId);
                
                return Ok(new
                {
                    message = "获取审计统计成功",
                    statistics = stats
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取审计统计失败");
                return StatusCode(500, new { message = "获取统计失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 测试分页查询审计日志
        /// </summary>
        [HttpGet("test-logs/{tenantId}")]
        public async Task<IActionResult> TestGetLogs(string tenantId, [FromQuery] int pageIndex = 0, [FromQuery] int pageSize = 10)
        {
            try
            {
                var filter = new AuditLogFilter
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    StartDate = DateTime.UtcNow.AddDays(-7), // 最近7天
                    SortBy = "Timestamp",
                    SortDescending = true
                };

                var result = await _auditService.GetLogsAsync(tenantId, filter);
                
                return Ok(new
                {
                    message = "查询审计日志成功",
                    totalCount = result.TotalCount,
                    pageIndex = result.PageIndex,
                    pageSize = result.PageSize,
                    totalPages = result.TotalPages,
                    logs = result.Items.Select(log => new
                    {
                        log.Id,
                        log.Type,
                        log.Content,
                        log.UserId,
                        log.UserName,
                        log.Timestamp,
                        log.Result,
                        log.IP
                    })
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询审计日志失败");
                return StatusCode(500, new { message = "查询失败", error = ex.Message });
            }
        }
    }
}
